package com.ruoyi.business.service.impl;

import com.ruoyi.activiti.domain.IProcessInstance;
import com.ruoyi.business.domain.LeaveRequestForm;
import com.ruoyi.business.mapper.LeaveRequestFormMapper;
import com.ruoyi.business.service.LeaveRequestFormService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author danghf
 * @date 2024/04/27 18:26:01
 */
@Service
public class LeaveRequestFormServiceImpl implements LeaveRequestFormService {
    private static final Logger logger = LoggerFactory.getLogger(LeaveRequestFormServiceImpl.class);

    private final LeaveRequestFormMapper mapper;
    private final RuntimeService runtimeService;
    private final TaskService taskService;

    public final String PROCESS_DEFINITION_KEY = "leave";

    public LeaveRequestFormServiceImpl(LeaveRequestFormMapper mapper, RuntimeService runtimeService, TaskService taskService) {
        this.mapper = mapper;
        this.runtimeService = runtimeService;
        this.taskService = taskService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult start(LeaveRequestForm form, Map<String, Object> map, ProcessDefinition processDefinition) {
        Long userId = SecurityUtils.getUserId();
        // 插入表单
        form.setStatus(0);
        form.setUserId(userId);
        mapper.insertOne(form);
        // 启动流程
        map.put("assignee", userId);
        // 设置流程的发起者
        Authentication.setAuthenticatedUserId(userId.toString());
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(), form.getId().toString(), map);
        // 判断该执行人是否可以执行当前任务，如果可以，执行完成当次任务
        // start(启动任务) -> 创建(执行) -> ... -> end
        // 任务执行人是当前用户，执行任务
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstance.getProcessInstanceId())
                .taskAssignee(userId.toString())
                .singleResult();
        if (task != null){
            taskService.complete(task.getId());
        }
        return AjaxResult.success();
    }

    @Override
    public int insertOne(LeaveRequestForm leaveRequestForm) {
        return mapper.insertOne(leaveRequestForm);
    }


    @Override
    public LeaveRequestForm selectLeaveRequestFormById(Long id) {
        return mapper.selectLeaveRequestFormById(id);
    }
}
